import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { user } from "@/servers/user";

// 异步 action: 获取用户信息
export const fetchUserInfo = createAsyncThunk(
  "user/fetchUserInfo",
  async (_, { rejectWithValue }) => {
    try {
      return await user.getInfo();
    } catch (error) {
      return rejectWithValue(error.message || "获取用户信息失败");
    }
  }
);

// 异步 action: 登录
export const login = createAsyncThunk(
  "user/login",
  async ({ email, code }, { rejectWithValue }) => {
    try {
      return await user.login(email, code);
    } catch (error) {
      return rejectWithValue(error.message || "登录失败");
    }
  }
);

// 异步 action: 注销
export const logout = createAsyncThunk(
  "user/logout",
  async (_, { rejectWithValue }) => {
    try {
      await user.logout();
      return null;
    } catch (error) {
      return rejectWithValue(error.message || "注销失败");
    }
  }
);

// 异步 action: 订阅站点
export const subscribe = createAsyncThunk(
  "user/subscribe",
  async (ids, { getState, rejectWithValue }) => {
    try {
      const { currentUser } = getState().user;
      if (!currentUser) {
        return {
          subscribe_list: ids,
        };
      }
      return await user.subscribe(ids);
    } catch (error) {
      return rejectWithValue(error.message || "订阅失败");
    }
  }
);

// 异步 action: 更新列表显示模式
export const updateListDisplay = createAsyncThunk(
  "user/updateListDisplay",
  async (listDisplay, { getState, rejectWithValue }) => {
    try {
      const { currentUser } = getState().user;
      if (!currentUser) {
        return {
          config: { list_display: listDisplay },
        }
      }
      return await user.updateListDisplay(listDisplay);
    } catch (error) {
      return rejectWithValue(error.message || "更新显示模式失败");
    }
  }
);

// 异步 action: 更新新窗口打开模式
export const updateOpenInNewWindow = createAsyncThunk(
  "user/updateOpenInNewWindow",
  async (openInNewWindow, { getState, rejectWithValue }) => {
    try {
      const { currentUser } = getState().user;
      if (!currentUser) {
        return {
          config: { open_in_new_window: openInNewWindow },
        };
      }
      return await user.updateOpenInNewWindow(openInNewWindow);
    } catch (error) {
      return rejectWithValue(error.message || "更新窗口打开模式失败");
    }
  }
);

// 用户状态 slice
const userSlice = createSlice({
  name: "user",
  initialState: {
    currentUser: null,
    subscribes: [],
    listDisplay: 0, // 0: 完整模式, 1: 简约模式
    openInNewWindow: true,
    loading: false,
    error: null,
  },
  reducers: {
    // 重置错误状态
    resetError: (state) => {
      state.error = null;
    },
    // 清除用户信息
    clearUser: (state) => {
      state.currentUser = null;
      state.subscribes = [];
      state.listDisplay = 0;
      state.openInNewWindow = true;
    },
  },
  extraReducers: (builder) => {
    // 处理获取用户信息
    builder
      .addCase(fetchUserInfo.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchUserInfo.fulfilled, (state, action) => {
        state.loading = false;
        state.currentUser = action.payload;
        state.subscribes = action.payload?.subscribed_hotspots || [];
        state.listDisplay = action.payload?.config.list_display || 0;
        state.openInNewWindow = action.payload?.config.open_in_new_window || true;
      })
      .addCase(fetchUserInfo.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload;
      })
      
    // 处理登录
      .addCase(login.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(login.fulfilled, (state, action) => {
        state.loading = false;
        state.currentUser = action.payload;
        state.subscribes = action.payload?.subscribed_hotspots || [];
        state.listDisplay = action.payload?.config.list_display || 0;
        state.openInNewWindow = action.payload?.config.open_in_new_window || true;
      })
      .addCase(login.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload;
      })
      
    // 处理注销
      .addCase(logout.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(logout.fulfilled, (state) => {
        state.loading = false;
        state.currentUser = null;
        state.subscribes = [];
      })
      .addCase(logout.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload;
      })
      
    // 处理订阅
      .addCase(subscribe.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(subscribe.fulfilled, (state, action) => {
        state.loading = false;
        state.subscribes = action.payload?.subscribe_list || state.subscribes;
      })
      .addCase(subscribe.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload;
      })
      
    // 处理更新列表显示模式
      .addCase(updateListDisplay.fulfilled, (state, action) => {
        state.listDisplay = action.payload?.config.list_display == undefined ? state.listDisplay : action.payload?.config.list_display;
      })
      
    // 处理更新窗口打开模式
      .addCase(updateOpenInNewWindow.fulfilled, (state, action) => {
        state.openInNewWindow = action.payload?.config.open_in_new_window == undefined ? state.openInNewWindow : action.payload?.config.open_in_new_window;
      });
  },
});

export const { resetError, clearUser } = userSlice.actions;

export default userSlice.reducer;